# -*-coding:utf-8-*-
import baostock as bs
import pandas as pd
import traceback
from sqlalchemy import create_engine


class HanderBaoData:
    """
    BaoStock
    通过开源量化金融数据接口获取数据
    """
    # 登录信息
    lg = ''
    # 接口返回结果信息
    rs = ''

    def __init__(self):
        # 清空结果数据
        self.res_data = ''
        # 初始化时进行登录
        # self._login()

    def _login(self):
        """
        登录系统
        """
        self.lg = bs.login()

    def _logout(self):
        """
        登出系统
        """
        bs.logout()

    def _get_login_msg(self):
        """
        获取登录的错误信息
        """
        if self.lg.error_code != 0:
            print('login respond error_code:'+self.lg.error_code)
        if self.lg.error_msg != 'success':
            print('login respond  error_msg:'+self.lg.error_msg)

    def _set_k_params(self):
        """
        turn:换手率
        volume:成交量
        """
        # 设置K线日线获取参数
        self.k_d_params = {
            'index_': 'date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST',
            'frequency': 'd',
            'adjustflag': '3'
        }

    def _set_k_code(self, k_code=None):
        """
        设置K线的股票代码
        """
        self.k_code = k_code

    def _set_k_date(self, start_date='', end_date=''):
        """
        设置K线的开始结束，日期
        self.k_start_date = '2021-05-26'
        self.k_end_date = '2021-05-27'
        """
        self.k_start_date = start_date
        self.k_end_date = end_date

    def _get_k_data(self):
        """
        获取沪深A股历史K线数据
        """
        self.rs = bs.query_history_k_data_plus(self.k_code,
                                               self.k_d_params['index_'],
                                               start_date=self.k_start_date, end_date=self.k_end_date,
                                               frequency=self.k_d_params['frequency'], adjustflag=self.k_d_params['adjustflag'])

    def _get_rs_error(self):
        """
        打数据接口误信息
        """
        print('query_history_k_data_plus respond error_code:'+self.rs.error_code)
        print('query_history_k_data_plus respond  error_msg:'+self.rs.error_msg)

    def _handle_data_res(self):
        """
        将接口结果处理成DF数据
        """
        data_list = []
        while (self.rs.error_code == '0') & self.rs.next():
            # 获取一条记录，将记录合并在一起
            data_list.append(self.rs.get_row_data())
        self.res_data = pd.DataFrame(data_list, columns=self.rs.fields)

    def get_df_res_data(self):
        """
        获取DF结构的数据
        """
        return self.res_data

    def res_to_csv(self, out_file=None):
        """
        将数据保存在csv中
        """
        if out_file is None:
            return False
        self.res_data.to_csv(out_file, index=False)

    def set_db_con(self, cfg=None):
        """
        设置数据库连接
        """
        self.con = create_engine(
            'mysql+pymysql://'+cfg.CONFIG['db']['default']['username']+':'+cfg.CONFIG['db']['default']['pwd']+'@'+cfg.CONFIG['db']['default']['host']+':'+cfg.CONFIG['db']['default']['port']+'/'+cfg.CONFIG['db']['default']['dbname']+'?charset=utf8')

    def res_to_db(self, pd_data2, table_name=None):
        """
        将结果导入数据库
        """
        if table_name is None:
            return False
        try:

            pd.io.sql.to_sql(pd_data2, table_name, self.con,
                             if_exists="append", index=False)
        except Exception as ee:
            print("导入数据库失败")
            print("error >>>", ee)
            traceback.print_exc()
        else:
            print("导入数据库-end---"+table_name)
        finally:
            return 1

    def get_data_by_date(self, table_name=None, date_=None):
        """
        根据时间获取股票的信息
        """
        sql_ = "select * from `{0}` where date='{1}'".format(table_name, date_)
        data = pd.read_sql(sql_, self.con)
        return data
